package estore.service;

import estore.model.Product;

import java.io.*;
import java.util.*;

public class ProductService {
    private final Map<String, Product> productData = new HashMap<>();
    private String dataFilePath;
    private static final String CONFIG_FILE = "config.properties";
    private static final String DEFAULT_DATA_FILE = "products.dat";

    public ProductService() {
        loadConfig();
        loadData();
    }
    private void loadConfig() {
        Properties props = new Properties();
        try (InputStreamReader isr = new InputStreamReader(
                new FileInputStream(CONFIG_FILE), "UTF-8")) {
            props.load(isr);
            dataFilePath = props.getProperty("data.file.path", DEFAULT_DATA_FILE);
        } catch (FileNotFoundException e) {
            System.out.println("配置文件不存在，使用默认路径: " + DEFAULT_DATA_FILE);
            dataFilePath = DEFAULT_DATA_FILE;
        } catch (IOException e) {
            e.printStackTrace();
            dataFilePath = DEFAULT_DATA_FILE;
        }
    }
    public void saveData() {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(dataFilePath))) {
            oos.writeObject(productData);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void loadData() {
        File file = new File(dataFilePath);
        if (file.exists()) {
            try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(dataFilePath))) {
                Object obj = ois.readObject();
                if (obj instanceof Map) {
                    productData.clear();
                    productData.putAll((Map<String, Product>) obj);
                }
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        else {
            // 初始化默认商品数据（无重复）
            Set<String> javaBookTags = new HashSet<>();
            javaBookTags.add("编程");
            javaBookTags.add("畅销");
            productData.put("p001", new Product("p001", "Java从入门到精通", 99.0, 100, javaBookTags));

            Set<String> dbBookTags = new HashSet<>();
            dbBookTags.add("数据库");
            dbBookTags.add("高性能");
            productData.put("p002", new Product("p002", "高性能MySQL", 128.5, 50, dbBookTags));

            Set<String> duplicateTagSet = new HashSet<>();
            duplicateTagSet.add("热门");
            duplicateTagSet.add("热门"); // 验证Set唯一性
            productData.put("p003", new Product("p003", "领域驱动设计", 45.8, 200, duplicateTagSet));

            productData.put("p004", new Product("p004", "生发秘籍", 88.8, 0));
        }
    }


    // 原有业务方法（getAllProducts、findProductById）保持不变
    public List<Product> getAllProducts() {
        return new ArrayList<>(productData.values());
    }

    public Product findProductById(String id) {
        return productData.get(id);
    }
    public void backupData() {
        String backupFilePath = dataFilePath + ".bak"; // 备份文件路径（原文件加.bak后缀）
        try (FileInputStream fis = new FileInputStream(dataFilePath);
             FileOutputStream fos = new FileOutputStream(backupFilePath)) {
            byte[] buffer = new byte[1024]; // 1KB缓冲区
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead); // 将缓冲区数据写入备份文件
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("数据备份失败：" + e.getMessage());
        }
    }
}

        /**
         * 构造函数，初始化商品数据
         */



// 将ProductSorters提取为独立的public类
